<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分类管理 - 广告管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .table-container {
            margin-top: 20px;
        }
        .btn-group {
            gap: 5px;
        }
        .category-actions {
            white-space: nowrap;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <div class="row">
            <div class="col-12">
                <h1 class="mb-4">
                    <i class="bi bi-tags"></i> 分类管理
                </h1>
                
                <!-- 导航按钮 -->
                <div class="mb-3">
                    <a href="/web/ads" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-left"></i> 返回广告列表
                    </a>
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addCategoryModal">
                        <i class="bi bi-plus-circle"></i> 添加分类
                    </button>
                </div>

                <!-- 分类列表 -->
                <div class="table-container">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title mb-0">
                                <i class="bi bi-list-ul"></i> 分类列表
                            </h5>
                        </div>
                        <div class="card-body">
                            <div th:if="${message}" class="alert alert-info" role="alert" th:text="${message}"></div>
                            <div th:if="${error}" class="alert alert-danger" role="alert" th:text="${error}"></div>
                            
                            <div th:if="${categories != null and !#lists.isEmpty(categories)}">
                                <table class="table table-striped table-hover">
                                    <thead class="table-dark">
                                        <tr>
                                            <th style="width: 10%;">ID</th>
                                            <th style="width: 60%;">分类名称</th>
                                            <th style="width: 30%;">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr th:each="category : ${categories}">
                                            <td th:text="${category.id}"></td>
                                            <td>
                                                <span class="fw-bold" th:text="${category.type}"></span>
                                            </td>
                                            <td class="category-actions">
                                                <div class="btn-group" role="group">
                                                    <button type="button" 
                                                            class="btn btn-sm btn-outline-primary edit-category-btn"
                                                            th:data-id="${category.id}"
                                                            th:data-type="${category.type}">
                                                        <i class="bi bi-pencil"></i> 编辑
                                                    </button>
                                                    <button type="button" 
                                                            class="btn btn-sm btn-outline-danger delete-category-btn"
                                                            th:data-id="${category.id}"
                                                            th:data-type="${category.type}">
                                                        <i class="bi bi-trash"></i> 删除
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            
                            <div th:if="${categories == null or #lists.isEmpty(categories)}" class="text-center py-4">
                                <div class="mb-3">
                                    <i class="bi bi-folder-x" style="font-size: 3rem; color: #6c757d;"></i>
                                </div>
                                <p class="text-muted mb-3">暂无分类数据</p>
                                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addCategoryModal">
                                    <i class="bi bi-plus-circle"></i> 添加第一个分类
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加分类模态框 -->
    <div class="modal fade" id="addCategoryModal" tabindex="-1" aria-labelledby="addCategoryModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addCategoryModalLabel">
                        <i class="bi bi-plus-circle"></i> 添加分类
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="addCategoryForm">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="addCategoryType" class="form-label">分类名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="addCategoryType" name="type" required 
                                   placeholder="请输入分类名称">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-circle"></i> 添加
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 编辑分类模态框 -->
    <div class="modal fade" id="editCategoryModal" tabindex="-1" aria-labelledby="editCategoryModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editCategoryModalLabel">
                        <i class="bi bi-pencil"></i> 编辑分类
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="editCategoryForm">
                    <div class="modal-body">
                        <input type="hidden" id="editCategoryId" name="id">
                        <div class="mb-3">
                            <label for="editCategoryType" class="form-label">分类名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="editCategoryType" name="type" required 
                                   placeholder="请输入分类名称">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-circle"></i> 保存
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 添加分类
        document.getElementById('addCategoryForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const categoryData = {
                type: formData.get('type')
            };

            fetch('/web/api/categories', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(categoryData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('分类添加成功！');
                    location.reload();
                } else {
                    alert('添加失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('添加失败，请稍后重试');
            });
        });

        // 编辑分类按钮事件委托
        document.addEventListener('click', function(e) {
            if (e.target.closest('.edit-category-btn')) {
                const btn = e.target.closest('.edit-category-btn');
                const id = btn.getAttribute('data-id');
                const type = btn.getAttribute('data-type');
                editCategory(id, type);
            }
        });

        // 删除分类按钮事件委托
        document.addEventListener('click', function(e) {
            if (e.target.closest('.delete-category-btn')) {
                const btn = e.target.closest('.delete-category-btn');
                const id = btn.getAttribute('data-id');
                const type = btn.getAttribute('data-type');
                deleteCategory(id, type);
            }
        });

        // 编辑分类
        function editCategory(id, type) {
            document.getElementById('editCategoryId').value = id;
            document.getElementById('editCategoryType').value = type;
            new bootstrap.Modal(document.getElementById('editCategoryModal')).show();
        }

        document.getElementById('editCategoryForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const categoryId = formData.get('id');
            const categoryData = {
                type: formData.get('type')
            };

            fetch('/web/api/categories/' + categoryId, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(categoryData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('分类更新成功！');
                    location.reload();
                } else {
                    alert('更新失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('更新失败，请稍后重试');
            });
        });

        // 删除分类
        function deleteCategory(id, type) {
            if (confirm('确定要删除分类 "' + type + '" 吗？\n\n注意：删除分类可能会影响相关的广告数据。')) {
                fetch('/web/api/categories/' + id, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('分类删除成功！');
                        location.reload();
                    } else {
                        alert('删除失败：' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除失败，请稍后重试');
                });
            }
        }
    </script>
</body>
</html>